package com.dxl.web.account.interceptor;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;

import com.dxl.common.annotation.RequirePermission;
import com.dxl.common.spring.AppCtxHolder;
import com.dxl.common.utils.BeanUtils;
import com.dxl.common.utils.Utils;
import com.dxl.dao.common.context.SessionContext;
import com.dxl.service.account.AccountService;
import com.dxl.service.optlog.OptLogService;

public class PermissionIntercepter implements MethodInterceptor {
	private static final Logger LOG = Logger.getLogger(PermissionIntercepter.class);
	
	public Object invoke(MethodInvocation mi) throws Throwable {
		Method method = mi.getMethod();
		RequirePermission rp = (RequirePermission) BeanUtils.getMethodOrClassAnnotation(method, RequirePermission.class);
//		AppCtxHolder.getBean(OptLogService.class).addLog(rp);
		if (Utils.isNotNull(rp)) {
			String[] functions = rp.value();
			if (AppCtxHolder.getBean(AccountService.class).hasPermission(SessionContext.getSessionId(), functions)) {
				LOG.info("用户[" + SessionContext.getAccountName() + "]有权限：" + Utils.join(functions, ","));
			} else {
				LOG.info("用户[" + SessionContext.getAccountName() + "]没有权限：" + Utils.join(functions, ","));
				throw new Exception("亲，您没有权限执行该操作哟~");
			}
		}
		return mi.proceed();
	}
}
